<template>
  <el-dialog
    :title="title"
    width="600px"
    :visible.sync="visible"
    :before-close="handleClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" style="padding-right: 25px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button size="small" type="primary" :loading="loading" @click="submitForm('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { login } from '@/api/user'

export default {
  name: 'ValidateIdentity',
  props: {
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        userName: '',
        password: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      title: '确认身份',
      loading: false
    }
  },
  methods: {
    handleClose() {
      this.resetForm('ruleForm')
      this.$emit('update:visible', false)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const userName = this.ruleForm.userName.trim()
          const password = this.ruleForm.password.trim()
          login({ username: userName, password }).then(response => {
            const { code } = response
            if (code === 20000) {
              this.$emit('onConfirm')
              this.handleClose()
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
